//
//  CLCommonSuperViewFind.m
//  Charles
//
//  Created by Charles on 2019/7/16.
//  Copyright © 2019 charles. All rights reserved.
//

#import "CLCommonSuperViewFind.h"

@implementation CLCommonSuperViewFind

- (NSArray *)findCommonSuperViewWithView:(UIView *)view anotherView:(UIView *)anotherView {
    NSMutableArray *resultArray = [[NSMutableArray alloc]init];
    // 查找第一个视图的所有父视图
    NSArray *firstSuperviews = [self findSuperView:view];
    // 查找第二个视图的所有父视图
    NSArray *secondSuperviews = [self findSuperView:anotherView];
    
    int index = 0;
    while (index < MIN(firstSuperviews.count, secondSuperviews.count)) {
        // 倒序方式获取各个视图的父视图
        UIView *firstSuperView = [firstSuperviews objectAtIndex:firstSuperviews.count - index - 1];
        UIView *secondSuperView = [secondSuperviews objectAtIndex:secondSuperviews.count - index - 1];
        // 如果相等，则为共同父视图
        if (firstSuperView == secondSuperView) {
            [resultArray addObject:firstSuperView];
            index++;
        }
        // 如果不相等则结束遍历
        else {
            break;
        }
    }
    return resultArray;
}

- (NSArray *)findSuperView:(UIView *)view {
    // 获取传进来的视图的父视图
    UIView *tempView = view.superview;
    // 初始化结果数组
    NSMutableArray *result = [[NSMutableArray alloc]initWithCapacity:0];
    while (tempView) {
        [result addObject:tempView];
        // 顺着superview一直向上查找
        tempView = tempView.superview;
    }
    return result;
}

@end
